package com.randb.easyhttp.interceptor;

import android.content.Context;
import android.text.TextUtils;

import com.randb.easyhttp.utils.HttpLog;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * User: RandBII
 * Date: 2020/5/27
 * Description:
 */
public class CacheInterceptor implements Interceptor {

    protected Context context;
    protected String cacheControlValue_offline;
    protected String cacheControlValue_online;
    protected static final int maxStale = 60 * 60 * 24 * 3;
    protected static final int maxStaleOnline = 60;

    public CacheInterceptor(Context context) {
        this(context, String.format("max-age=%d", maxStaleOnline));
    }

    public CacheInterceptor(Context context, String cacheControlValue_offline) {
        this(context, cacheControlValue_offline, String.format("max-age=%d", maxStaleOnline));
    }

    public CacheInterceptor(Context context, String cacheControlValue_offline, String cacheControlValue_online) {
        this.context = context;
        this.cacheControlValue_offline = cacheControlValue_offline;
        this.cacheControlValue_online = cacheControlValue_online;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {

        Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");
        HttpLog.e(maxStaleOnline + "s load cache:" + cacheControl);

        if (TextUtils.isEmpty(cacheControl)
                || cacheControl.contains("no-store")
                || cacheControl.contains("no-cache")
                || cacheControl.contains("must-revalidate")
                || cacheControl.contains("max-age")
                || cacheControl.contains("max-stale")) {
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age" + maxStale)
                    .build();

        }
        return originalResponse;
    }


}
